<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\MyLog;
use App\Models\Mongodb;
use App\Models\Wallet;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

require_once('config.php');
require_once('function.php');
require_once('moban.php');

class TixianController extends Controller
{

    public function tixian(Request $request)
    {

        /*
        * 配置内容可以修改
        * 微信小程序配置
        * 用于微信企业付款
        */

        $cpy_appid = env('APP_ID');                  //小程序appid
        $cpy_mchid = env('WXPAY_MCHID');                          //商户id
        $cpy_key =  env('WXPAY_API_KEY');      //商户key
        $cpy_secret = env('APP_SECRET');   //公众号secret
        $cpy_nonce_str = time() . rand(100000, 999999);   //随机字符串
        $cpy_order_str = time() . rand(100000, 999999); // 唯一订单号


        //接收openid
        $cpy_openid = $request->openid;  //获取的用户openid
        $price = $request->price;    //获取交易价格
        $formId = $request->formId; //模板消息的formid

        if ($cpy_openid == '' || $price == '') {
            echo 'not';
            exit;
        }

        // //判断7天内只能提现1次
        // $tixianrecord = DB::table('tixian')->whereBetween('created_at', array(time()-604800,time()))->where('status',1)->get();
        // //资金池
        // $ordersum = DB::table('cdorder')->where('pay_status',1)->sum('price');
        // $tixiansum = DB::table('tixian')->where('status',1)->sum('price');
        // $shenhe = DB::table('shenhe')->where('status',0)->sum('price');
        // $total = $tixiansum+$shenhe+$price;

        // if ($total > $ordersum || $tixianrecord) { //判断资金池和7天提现次数
        //     echo 'deny';
        //     exit;
        // }

        //开启事务
        DB::beginTransaction();
        try {
            // 判断账户余额是否足够
            $money = DB::table('wallet')->where('openid', $cpy_openid)->lockForUpdate()->first();
            if (!$money || $money->money < $price || $money == '' || empty($money)) {//余额不足或不存在
                echo 'notenough';
                exit();
            }

            //金额大于20,走人工审核提现
            if ($price > 10) {
                $arr = [
                    'openid' => $cpy_openid,
                    'price' => $price,
                    'formid' => $formId,
                    'created_at' => time()
                ];
               $get =  DB::table('shenhe')->insert($arr);
               $in = DB::table('wallet')->where('openid', $cpy_openid)->decrement('money', $price);
               if ($get && $in) {
                   DB::commit();
                   echo 'success' ;
                   exit();
               }
               echo 'error';
               exit();
            }

            //自动提现
            $arr = [
                'openid' => $cpy_openid,
                'price' => $price
            ];
            $insertId = DB::table('tixian')->insertGetId($arr);

            //封装数据
            $ip = $_SERVER['REMOTE_ADDR'];
            $dataArr = array(
                'mch_appid' => $cpy_appid,
                'mchid' => $cpy_mchid,
                'nonce_str' => $cpy_nonce_str,
                'partner_trade_no' => $cpy_order_str,
                'openid' => $cpy_openid,
                'check_name' => 'NO_CHECK', //NO_CHECK 小额不校验真实姓名
                're_user_name' => 'test', //填写对应openid真实姓名
                'amount' => $price * 100, //以分为单位,必须大于100
                'desc' => '提现成功',  //入账详情
                'spbill_create_ip' => $ip,
            );
            //生成签名
            $sign = getSign($dataArr, $cpy_key);
            $xml = '<xml>
                    <mch_appid>' . $dataArr['mch_appid'] . '</mch_appid>
                    <mchid>' . $dataArr['mchid'] . '</mchid>
                    <nonce_str>' . $dataArr['nonce_str'] . '</nonce_str>
                    <partner_trade_no>' . $dataArr['partner_trade_no'] . '</partner_trade_no>
                    <openid>' . $dataArr['openid'] . '</openid>
                    <check_name>' . $dataArr['check_name'] . '</check_name>
                    <re_user_name>' . $dataArr['re_user_name'] . '</re_user_name>
                    <amount>' . $dataArr['amount'] . '</amount>
                    <desc>' . $dataArr['desc'] . '</desc>
                    <spbill_create_ip>' . $dataArr['spbill_create_ip'] . '</spbill_create_ip>
                    <sign>' . $sign . '</sign>
                    </xml>';
            $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
            if ($insertId) {
                $res = xmlToArray(postXmlCurl($xml, $url, true));
                $result = $this->update_money($cpy_openid, $price, $res, $formId,$insertId);
                if ($result == 'success') {
                    $in = DB::table('wallet')->where('openid', $cpy_openid)->decrement('money', $price);
                    $logs = Mongodb::connectionMongodb('hb_log');
                    $logs->insert(['openid' => $cpy_openid, 'type' => '3', 'name' => '提现成功', 'message' => $price, 'log_time' => date("Y-m-d H:i")]);
                }
                DB::commit();
                echo $result;exit;
            }
        } catch (\Exception $e) {
            DB::rollBack();
             $mylog = new MyLog;
             $mylog->setLog('用户提现数据:'.$e,$logPath='tixian');
            echo 'error';exit;
        }
    }


    //修改用户余额
    public function update_money($cpy_openid, $price, $res, $formId,$insertId)
    {
        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
            //记录提现
            $arr = [
                'partner_trade_no' => $res['partner_trade_no'],
                'payment_no' => $res['payment_no'],
                'payment_time' => $res['payment_time'],
                'created_at' => time(),
                'status' => 1
            ];
            DB::table('tixian')->where('id',$insertId)->update($arr);
            //发送模板消息调用(提现成功)
            $this->templateInfo($price, $res, $cpy_openid, $formId);
            return 'success';
        }elseif ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'FAIL' && $res['err_code'] == 'SENDNUM_LIMIT') {//当天提现次数超额，返回提示
            $arr = [
                'err_code' => $res['err_code_des'],
                'created_at' => time()
            ];
            DB::table('tixian')->where('id',$insertId)->update($arr);
            return 'chao'; //超额提示
        } elseif ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'FAIL') {//通信成功，但交易失败，写入数据库
            $arr = [
                'err_code' => $res['err_code_des'],
                'created_at' => time()
            ];
            DB::table('tixian')->where('id',$insertId)->update($arr);
            return 'error'; //联系管理员
        }else {//通讯失败，返回错误
            return 'error';
        }
    }


//模板消息
    public function templateInfo($price, $res, $cpy_openid, $formId)
    {
        $moban = new \Moban();
        $mobanData = [
            'keyword1' => ['value' => $price . '元'],
            'keyword2' => ['value' => $res['payment_time']],
            'keyword3' => ['value' => '微信钱包'],
            'keyword4' => ['value' => '请注意查收']
        ];
        $get = $moban->send($cpy_openid, 'ztcKAjmN4w7hjsF02f5Xlyv74SlGpcLHcZREgd3JX4c', 'pages/voice_box/mention/index', $formId, $mobanData);
        //将回调数据写入日志
        $tuiData = '[openid]' . $cpy_openid . '[price]' . $price . '[errmsg]' . $get->errmsg;
        $mylog = new MyLog;
        $mylog->setLog('用户提现数据:' . $tuiData, $logPath = 'moban(tixian)');

    }


    //超时退回(定时任务)
    public function tui()
    {
        //条件
        $where = [
            ['s_price', '>', 0],
            ['s_number', '>', 0],
            ['is_return', '=', 0],
            ['status', '=', 1]
        ];
        $data = DB::table('redf')->where($where)->get();
        foreach ($data as $value) {
            if ($value->created_at + 86400 < time()) {//退回零钱
                $re = DB::table('wallet')->where('openid', $value->openid)->increment('money', $value->s_price); //增加余额
                $res = DB::table('redf')->where('id', $value->id)->update(['is_return' => 1]); //更新标识
                $arr = [
                    'openid' => $value->openid,
                    'redid' => $value->id,
                    'price' => $value->s_price,
                    'created_at' => time()
                ];
                if ($re && $res) {
                    DB::table('tui')->insert($arr);
                    if ($value->pay_type == 0) {
                        $pre = DB::table('cdorder')->where('order_sn', '=', $value->order_sn)->first();
                        $formid = $pre->prepay_id;
                    } else {
                        $formid = $value->formid;
                    }
                    //发送模板消息
                    $moban = new \Moban();
                    $mobanData = [
                        'keyword1' => ['value' => $value->s_price . '元'],
                        'keyword2' => ['value' => '口令红包\'' . $value->password . '\'未领完'],
                        'keyword3' => ['value' => '小程序账户余额'],
                        'keyword4' => ['value' => '点击此处查看账户余额']
                    ];
                    $get = $moban->send($value->openid, '58X7Ns2Y9eWNc8YQzq-UicP2cRAf_Az5nTrCnmyBWm8', '/pages/voice_box/mention/index', $formid, $mobanData);
                    $tuiData = '[redid]' . $value->id . '[price]' . $value->s_price . '[errmsg]' . $get->errmsg;
                    // echo $get->errmsg;
                    //将回调数据写入日志
                    $mylog = new MyLog;
                    $mylog->setLog('定时退款数据:' . $tuiData, $logPath = 'moban(tuikuan)');
                }
            }
        }
    }

    //动态口令
    public function kouling()
    {
        $data = DB::table('kouling')->get();
        $fen = DB::table('fenlei')->get();
        $arr = [];
        foreach ($data as $value) {
            foreach ($fen as $val) {
                if ($value->type_id == $val->id) {
                    $arr[$value->type_id]['name'] = $val->name;
                    $arr[$value->type_id]['content'][] = $value->content;
                }
            }
        }
        echo json_encode($arr);
    }

}